// pages/coupon/couponDetail/couponDetail.js
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userId: null,
        couponId: null,
        couponInfo: {},
        couponCode: null,
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            couponId: options.couponId,
            userId: wx.getStorageSync('userId')
        })
        this.getCouponInfo()
        this.getCouponCode()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    getCouponInfo: function() {
        const that = this
        let data = {
            coupon_list_id: this.data.couponId,
            paramter: 1
        }
        common.post('Coupon/user_coupon_list', data).then(function(res) {
            if (res.code == 204) {
                return
            }
            that.setData({
                couponInfo: res[0]
            })
        }).catch(function(e) {})
    },

    getCouponCode: function() {
        const that = this
        let data = {
            couponId: this.data.couponId
        }
        common.post('Qrcodes/create_coupon', data).then(function(res) {
            if (res.code == 204) {
                return
            }
            that.setData({
                couponCode: res
            })
        }).catch(function(e) {})
    },

    confirmUse: function() {
        if(this.data.isLoading){
            return
        }
        this.setData({
            isLoading: true
        })
        wx.showLoading({
            title: '请稍后'
        })
        const that = this
        let data = {
            coupon_list_id: this.data.couponId
        }
        common.post('Coupon/use_coupon', data).then(function(res) {
            that.setData({
                isLoading: false
            })
            wx.hideLoading()
            if (res.code == 204) {
                wx.showModal({
                    title: '提示',
                    content: res.error,
                    showCancel: false,
                    success(res) {}
                })
            } else {
                wx.showModal({
                    title: '提示',
                    content: '确认使用成功',
                    success(res) {
                        if (res.confirm) {
                            that.getCouponInfo()
                        }
                    }
                })
            }
        }).catch(function(e) {})
    }
})